package com.tapstitch.scm.common.utils;

import com.alibaba.fastjson.JSON;
import com.tapstitch.scm.common.utils.http.HttpClientHelper;
import com.tapstitch.scm.common.utils.model.ImageInfoModel;
import org.apache.commons.lang3.tuple.Pair;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ImageSizeUtil {

	static final InheritableThreadLocal<Boolean> THREAD_LOCAL_WEBP_SUPPORT = new InheritableThreadLocal<>();
	static final InheritableThreadLocal<Boolean> THREAD_LOCAL_HK_IMAGE_REPLACE = new InheritableThreadLocal<>();

	static final String DOMAIN_HK = "publichk.cdn.ajmall-group.com";
	static final String DOMAIN_SOURCE = "ajmall-vc-public-bucket.oss-us-west-1.aliyuncs.com";
	static final String DOMAIN_SOURCE_2 = "ajmall-vc-public-bucket.oss-accelerate.aliyuncs.com";

	/**
	 * description 当前域名换成香港cdn域名
	 * @param sourceImageUrl 图片链接
	 * @return java.lang.String
	**/
	public static String vc2Hk(String sourceImageUrl){
		if (StringUtils.isEmpty(sourceImageUrl)) {
			return sourceImageUrl;
		}
		if(sourceImageUrl.contains(DOMAIN_SOURCE)) {
			return sourceImageUrl.replaceAll(DOMAIN_SOURCE, DOMAIN_HK);
		}
		if(sourceImageUrl.contains(DOMAIN_SOURCE_2)) {
			return sourceImageUrl.replaceAll(DOMAIN_SOURCE_2, DOMAIN_HK);
		}
		return sourceImageUrl;
	}

	public static List<String> batchVc2Hk(List<String> sourceImageUrlList){
		return sourceImageUrlList.stream().map(ImageSizeUtil::vc2Hk).collect(Collectors.toList());
	}

	public static String convert2UseHkOss(String sourceImageUrl) {
		if (StringUtils.isEmpty(sourceImageUrl)) {
			return sourceImageUrl;
		}

		if(sourceImageUrl.contains("publicvc.cdn.ajmall-group.com")) {
			return sourceImageUrl.replaceAll("publicvc.cdn.ajmall-group.com", "publichk.cdn.ajmall-group.com");
		}else if(sourceImageUrl.contains("publicvc.cdn.shangohui.com")) {
			return sourceImageUrl.replaceAll("publicvc.cdn.shangohui.com", "publichk.cdn.ajmall-group.com");
		}
		return sourceImageUrl;
	}

	/**
	 * 香港oss路径替换为美西oss路径
	 * @param sourceImageUrl
	 * @return
	 */
	public static String convert2UseVcOss(String sourceImageUrl) {
		if (StringUtils.isEmpty(sourceImageUrl)) {
			return sourceImageUrl;
		}

		if(sourceImageUrl.contains("publichk.cdn.ajmall-group.com")) {
			return sourceImageUrl.replace("publichk.cdn.ajmall-group.com", "publicvc.cdn.ajmall-group.com");
		}else if(sourceImageUrl.contains("publichk.cdn.ajmall-group.com")) {
			return sourceImageUrl.replace("publichk.cdn.ajmall-group.com", "publicvc.cdn.shangohui.com");
		}
		return sourceImageUrl;
	}
	/**
	 * 清理ThreadLocal
	 */
	public static void clearThreadLocal() {
		THREAD_LOCAL_WEBP_SUPPORT.remove();
		THREAD_LOCAL_HK_IMAGE_REPLACE.remove();
	}

	/**
	 * 指定是否支持webp图片格式
	 */
	public static void setWebpSupport(boolean support) {
		THREAD_LOCAL_WEBP_SUPPORT.set(support);
	}

	public static boolean isWebpSupport() {
		return THREAD_LOCAL_WEBP_SUPPORT.get()==null?false:THREAD_LOCAL_WEBP_SUPPORT.get();
	}
	/**
	 * webp完成
	 */

	/**
	 * 是否可以替换成香港OSS
	 */
	public static void setReplace2HKOSSSupport(boolean support) {
		THREAD_LOCAL_HK_IMAGE_REPLACE.set(support);
	}

	public static boolean isReplace2HKOSSSupport() {
		return THREAD_LOCAL_HK_IMAGE_REPLACE.get()==null?false:THREAD_LOCAL_HK_IMAGE_REPLACE.get();
	}
	/**
	 * 香港oss完成
	 */


	private static final int default_quality = 80;

	/**
	 * 强制进行大小缩放，并且指定最小边长
	 * @param originalUrl
	 * @param targetShortEdgeLength
	 * @return
	 */
	public static String getForceResizeUrl(String originalUrl, int targetShortEdgeLength) {
		if(originalUrl == null){
			return "";
		}
		if (originalUrl.indexOf("?") != -1) {
			return originalUrl;
		}
		return originalUrl + "?x-oss-process=image/resize,s_"+targetShortEdgeLength+",limit_0/format,jpg" ;
	}

	/**
	 * 以最长边压缩，质量为 90
	 * @param originalUrl
	 * @param targetWidth
	 * @return
	 */
	public static String getResizeUrl(String originalUrl, int targetWidth) {
		return getResizeUrl(originalUrl, targetWidth, default_quality);
	}

	/**
	 * 以最长边压缩，并指定质量
	 * @param originalUrl
	 * @param targetWidth
	 * @return
	 */
	public static String getResizeUrl(String originalUrl, int targetWidth, int quality) {
		return getResizeUrl(originalUrl, targetWidth, quality, 0);
	}

	/**
	 * <pre>
	 * 图片格式转换
	 * @param originalUrl
	 * @param targetWidth
	 * @param quality
	 * @param formatType :
	 * 	0 - 如果支持webp则使用webp，不支持的，则使用jpg；
	 * 	1 - 即如果支持webp则使用webp，不支持的，则使用默认值；
	 * 	2 - 不做任何转换；
	 * 	3 - 强制使用jpg
	 * @return
	 * </pre>
	 */
	public static String getResizeUrl(String originalUrl, int targetWidth, int quality, int formatType) {
		if (StringUtils.isEmpty(originalUrl)) {
			return "";
		}
		if (originalUrl.indexOf("?") != -1) {
			return originalUrl;
		}
		String convert2jpg = "";
		switch (formatType) {
		case 0:
			if(isWebpSupport()) {
				convert2jpg = "/format,webp/interlace,1";
			}else {
				convert2jpg = "/format,jpg/interlace,1";
			}
			break;
		case 1:
			if(isWebpSupport()) {
				convert2jpg = "/format,webp/interlace,1";
			}
			break;
		case 2:
			break;
		case 3:
			convert2jpg = "/format,jpg/interlace,1";
			break;
		default:
			break;
		}
		return originalUrl + "?x-oss-process=image/resize,l_" + targetWidth+"/quality,Q_"+quality+convert2jpg;
	}

	public static List<String> getResizeUrl(List<String> originalUrls, int targetWidth){
		return getResizeUrl(originalUrls, targetWidth, default_quality);
	}

	public static String[] getResizeUrl(String[] originalUrls, int targetWidth){
		return getResizeUrl(originalUrls, targetWidth, default_quality);
	}

	public static List<String> getResizeUrl(List<String> originalUrls, int targetWidth, int quality){
		if(originalUrls == null || originalUrls.isEmpty()){
			return originalUrls;
		}
		int size = originalUrls.size();
		List<String> targetUrls = new ArrayList<>(size);
		for(int i = 0;i<size;i++){
			targetUrls.add(getResizeUrl(originalUrls.get(i), targetWidth, quality));
		}
		return targetUrls;
	}

	public static String[] getResizeUrl(String[] originalUrls, int targetWidth, int quality){
		if(originalUrls == null || originalUrls.length == 0){
			return originalUrls;
		}
		String[] tmp = new String[originalUrls.length];
		for(int i = 0;i<originalUrls.length;i++){
			tmp[i] = getResizeUrl(originalUrls[i], targetWidth, quality);
		}
		return tmp;
	}


	private static boolean isAjMallPic(String picUrl) {
		if(org.apache.commons.lang3.StringUtils.contains(picUrl, "shangohui.com")
				|| org.apache.commons.lang3.StringUtils.contains(picUrl, "yidianshihui.com")
				|| org.apache.commons.lang3.StringUtils.contains(picUrl, "ajmall-group.com")) {
			return true;
		}
		return false;
	}

	private static final String IMAGE_INFO_SEARCH_SUFFIX = "?x-oss-process=image/info";

	/**
	 * 检查图片尺寸是否符合规范
	 * 图片比例1:1，600*600像素(包含)到1200像素*1200像素(包含)；或900像素*1200像素；
	 * @return
	 */
	public static boolean checkImageSize(String picUrl) throws IOException {
		if(StringUtils.isEmpty(picUrl)) {
			return false;
		}
		final Pair<Integer, Integer> sizePair = getSizePair(picUrl);
		if (sizePair == null) {
			throw new NullPointerException("获取图片大小失败");
		}
		int width = sizePair.getKey();
		int height = sizePair.getValue();
		return checkImageSize(width, height);
	}

	public static Pair<Integer, Integer> getSizePair(String picUrl) {
		try {
			int width;
			int height;
			if (isAjMallPic(picUrl)) {
				String jsonResult = HttpClientHelper.read(picUrl + IMAGE_INFO_SEARCH_SUFFIX);
				ImageInfoModel imageInfoModel = JSON.parseObject(jsonResult, ImageInfoModel.class);
				width = Integer.parseInt(imageInfoModel.getImageWidth().getValue());
				height = Integer.parseInt(imageInfoModel.getImageHeight().getValue());
			} else {
				byte[] downloadImage = HttpClientHelper.download(picUrl);
				BufferedImage sourceImg = ImageIO.read(new ByteArrayInputStream(downloadImage));
				width = sourceImg.getWidth();
				height = sourceImg.getHeight();
			}
			return Pair.of(width, height);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static int minSize = 600;
	private static int middleSize = 900;
	private static int maxSize = 1200;

	public static boolean checkImageSize(int width, int height) {
		boolean isOk = false;

		if(width == height && width >= minSize){
			isOk = true;
		}

		if(width == middleSize && height == maxSize){
			isOk = true;
		}
		return isOk;
	}

	/**
	 * 最大边只要不超过MaxSize , 就能将短边补齐
	 */
	public static boolean canBeTransform(int width, int height) {
		int max = Math.max(width, height);
		return max <= maxSize && max >= minSize;
	}

	public static ByteArrayOutputStream compressByPx(InputStream inputStream, int width, int height, boolean equalProportion) throws IOException {
		BufferedImage bufferedImage=ImageIO.read(inputStream);
		int sWidth=bufferedImage.getWidth();
		int sHeight=bufferedImage.getHeight();
		int diffWidth=0;
		int diffHeight=0;
		if(equalProportion){
			if((double)sWidth/width>(double)sHeight/height){
				int height2=width*sHeight/sWidth;
				diffHeight=(height-height2)/2;
			}else if((double)sWidth/width<(double)sHeight/height){
				int width2=height*sWidth/sHeight;
				diffWidth=(width-width2)/2;
			}
		}
		BufferedImage nbufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		nbufferedImage.getGraphics().fillRect(0,0,width,height);//填充整个屏幕
		nbufferedImage.getGraphics().drawImage(bufferedImage, diffWidth, diffHeight, width-diffWidth*2, height-diffHeight*2, null); // 绘制缩小后的图
		final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ImageIO.write(nbufferedImage,"jpg",byteArrayOutputStream);
		inputStream.close();
		return byteArrayOutputStream;
	}

}
